<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

</body>
<script>
/*
function fn() {
  setTimeout(() => {
    return 123
  }, 0)
  // return undefined
}

console.log(fn())
*/

//如何掌握一个概念
//用途+特征
//回调函数
//用途: 用来接受异步代码执行结果
//特性: 以参数的形式传递到函数当中执行,接受结果
/*
function fn(callback) {
  setTimeout(() => {
    callback(123)
  }, 0)
  // return undefined
}
fn(function(data){
  console.log(data)
})
*/
//回调地狱
//特征: 多次嵌套
/*
fn(function(data1){
  console.log('data1',data1)
  fn(function(data2){
    console.log('data2',data2)
    fn(function(data3){
      console.log('data3',data3)
    })
  })
})
*/

//回顾promise语法
/*
let p = new Promise((resovle, reject)=>{
  //成功回调函数
  // resovle(123)
  reject({status: 400, message: '产生错误'})
})
p.then((data)=>{
  console.log(data)
}).catch((error)=>{
  console.log(error)
})
*/

//封装promise
function axios(){
  return new Promise((resovle, reject)=>{
    //成功回调函数
    // resovle(123)
    //失败回调函数
    reject({status: 400, message: '产生错误'})
  })
}
//错误写法
/*
axios({url:'url1'}).then((data1)=>{
  console.log('data1', data1)
  axios({url:'url2'}).then((data2)=>{
    console.log('data2', data2)
    axios({url:'url3'}).then((data3)=>{
      console.log('data3', data3)
    })
  })
})
*/
//链式调用解决回调地狱
/*
axios({url:'url1'}).then((data1)=>{
  console.log('data1', data1)
  return axios({url:'url2'})
}).then((data2)=>{
  console.log('data2', data2)
  return axios({url:'url3'})
}).then((data3)=>{
  console.log('data3', data3)
})
*/
// 异步函数
//用途:用简化promise的接收,以同步写法来写异步的代码
//特征:定义方法在前面async,在promise前面加上await
async function fn(){
  let data1 = await axios({url:'url1'})
  console.log('data1', data1)
  let data2 = await axios({url:'url2'})
  console.log('data2', data2)
  let data3 = await axios({url:'url3'})
  console.log('data3', data3)
}
fn()
</script>
</html>
